import ParseArray from "./t1.mjs";
import data from "./dat.mjs";

//var parseArray = new ParseArray();
//parseArray.start(data.goods, "goods");
var isArray = function (obj) {
  if (!obj) {
    // console.log("你传入的是一个空的元素,请传入一个数组,或者对象数组!");
    return;
  }
  var arrType = (typeof obj.push + "").toUpperCase();
  if (arrType == "UNDEFINED") {
    return false;
  } else {
    return true;
  }
};

var isObject = function (obj) {
  if (!isArray(obj)) {
    var objType = (typeof obj + "").toUpperCase();
    if (objType == "OBJECT") {
      return true;
    }
  }
  return false;
};

var isNumber = function (value) {
  var reg = /[0-9]/g;
  return reg.test(value);
};
//编写的内置方法=============================================================
//【拓展】
var getCreateTableSql = function (props) {
  return "`" + props + "` varchar(255) NOT NULL,\n";
};
var getTableSql = function (createSql, name) {
  var sql1 = "DROP TABLE IF EXISTS `" + name + "`;\n";
  var sql2 = "CREATE TABLE `" + name + "` (\n";
  var sql3 = "`id` int(11) NOT NULL AUTO_INCREMENT,\n";
  var sql4 = createSql;
  var sql5 = "`remark` varchar(255) DEFAULT NULL,\n";
  var sql6 = "PRIMARY KEY (`id`)\n";
  var sql7 = ") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
  var sql = sql1 + sql2 + sql3 + sql4 + sql5 + sql6 + sql7;
  console.log(sql + "\n");
  return sql;
};

var indexArrNum = 0; //记录插入的数量
var getInsertSql = function (allPropsArr, obj, tableName) {
  var insertSql = "";
  allPropsArr.forEach((item, index, arr) => {
    if (!isArray(obj[item])) {
      insertSql += obj[item] + ", ";
    } else {
      insertSql += indexArrNum + ", ";
    }
  });
  var sql1 = insertSql;
  var sql2 =
    "INSERT INTO `" + tableName + "` VALUES (NULL, " + sql1 + "'暂无备注');";
  console.log(sql2);
  return sql2;
};

//内部变量
var createSql = "";
var allPropsArr = [];
var upTableName = "";
var okCreateTable = true;
//执行初始化数据
var init = function () {
  allPropsArr = [];
};

var dealObject = function (obj, tableName) {
  init();
  if (isObject(obj)) {
    for (var props in obj) {
      createSql += getCreateTableSql(props);
      allPropsArr.push(props);
    }
    //得到当前的建表语句
    if (okCreateTable) {
      getTableSql(createSql, tableName);
      okCreateTable = false;
    }
    //得到当前的插入数据
    indexArrNum++;
    getInsertSql(allPropsArr, obj, tableName);
  }
};

//循环处理数组
var arrs = data.goods[0].foods;
//测试数据
var tableName = "goods";
if (isArray(arrs)) {
  if (arrs.length >= 1) {
    arrs.forEach((item, index, arr) => {
      dealObject(item, tableName);
    });
  }
}
